﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using RealtReview.DataAccess.Entities;
using RealtReview.DataAccess.Interfaces;

namespace RealtReview.DataAccess.Repositories
{
    public class Repository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly DbContext context;

        public Repository(DbContext context)
        {
            this.context = context;
        }

        protected DbContext Context
        {
            get
            {
                return context;
            }
        }

        /// <summary>
        /// DbSet for current entity type.
        /// </summary>
        protected virtual IDbSet<T> DbSet
        {
            get
            {
                return context.Set<T>();
            }
        }

        public T InsertOrUpdate(T entity)
        {
            DbSet.Add(entity);
            return entity;
        }

        public void Delete(T entity)
        {
            DbSet.Remove(entity);
        }

        public T Get(Guid id)
        {
            return DbSet.FirstOrDefault(x => x.Id == id);
        }

        public IEnumerable<T> Get(IList<Func<T, bool>> predicates)
        {
            return predicates.Aggregate<Func<T, bool>, IEnumerable<T>>(DbSet, (current, p) => current.Where(p));
        }

        public IEnumerable<T> Get(Func<T, bool> predicate)
        {
             return DbSet.Where(predicate).AsEnumerable();
        }

        public void SaveChanges()
        {
            this.context.SaveChanges();
        }
    }
}
